package cn.utry.sipGateWay.netty;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.utry.sipGateWay.config.SiriConfig;
import cn.utry.sipGateWay.sip.SipMessageUtil;
import cn.utry.sipGateWay.sip.SipSession;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;

public class RtpServer {
	private int port;
	
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
	}
	private static final Logger log = LoggerFactory.getLogger(RtpServer.class);
	public  void Start(SipSession sipSession) throws InterruptedException {
			EventLoopGroup group = new NioEventLoopGroup();
			try {
				Bootstrap bootstrap = new Bootstrap();
				bootstrap.group(group).channel(NioDatagramChannel.class)
						.handler(new ChannelInitializer<NioDatagramChannel>() {
							@Override
							protected void initChannel(NioDatagramChannel ch) {
								ChannelPipeline pipeline = ch.pipeline();
								pipeline.addLast(new SipMsgHandler());
							}
						});
				Channel channel = bootstrap.bind(this.getPort()).sync().channel();
				log.info("创建了接收返回消息的服务  port:{}",this.getPort());
				InetSocketAddress address = new InetSocketAddress(SiriConfig.SERVER_IP, SiriConfig.SERVER_PORT);
				String inviteMsg=SipMessageUtil.getInviteMsg(sipSession.getInviteMap(),SiriConfig.TransFer_IP,SiriConfig.SERVER_IP);
				ByteBuf byteBuf = Unpooled.copiedBuffer(inviteMsg.getBytes(StandardCharsets.UTF_8));
				log.info("向服务{}:{}发送invite ",SiriConfig.SERVER_IP,SiriConfig.SERVER_PORT);
				log.info("\n {}",inviteMsg);
				channel.writeAndFlush(new DatagramPacket(byteBuf, address)).sync();
				channel.closeFuture().await();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				group.shutdownGracefully();
			}
		
	}
}
